package com.zsyh.jiujiu.home;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.zyh.toolslib.base.BaseActivity;
import com.example.zyh.toolslib.utils.SPUtils;
import com.example.zyh.toolslib.widget.TitleBar;
import com.google.gson.Gson;
import com.lwb.retrofit.RetrofitTask;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zsyh.jiujiu.Api;
import com.zsyh.jiujiu.R;
import com.zsyh.jiujiu.bean.GoodBean;
import com.zsyh.jiujiu.net.MyObserver;
import com.zsyh.jiujiu.weight.PopClassType;
import com.zsyh.jiujiu.weight.PopShaiXuan;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @ProjectName: livvehelp
 * @Package: com.zsyh.lsb.ui
 * @ClassName:
 * @Description: java类作用描述 分类获取
 * @Author: zsyh
 * @CreateDate: 2020/9/7 11:59
 * @UpdateUser: liangwanbo
 * @UpdateDate: 2020/9/7 11:59
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class ClassTypeActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.classtype)
    TextView classtype;
    @BindView(R.id.reclasstype)
    RelativeLayout reclasstype;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.reprice)
    RelativeLayout reprice;
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.recity)
    RelativeLayout recity;
    @BindView(R.id.shaixuan)
    TextView shaixuan;
    @BindView(R.id.reshaixuan)
    RelativeLayout reshaixuan;
    @BindView(R.id.rvlist)
    RecyclerView rvlist;
    @BindView(R.id.lin_title)
    LinearLayout linTitle;
    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R.id.priceimage)
    ImageView priceimage;
    private String titlename;
    private PopupWindow popupBigPhoto;
    int pageNumber = 1;//页数
    String pageSize = "10";//	每页条数
    String typeId;//分类一级id
    String cityId;//城市id
    String userGroup;//企业清库时（userGruop=企业）其余不传
    String isNew;//换限制时（isNew=闲置）其余不传
    String startPrice;//价格区间 开始
    String endPrice;//价格区间 结束
    String name;//搜索关键词
    String userType;//用户等级 传数字 1注册用户 2包月用户 3包年用户
    String classType;//换产品 classType=产品 换服务 classType=服务
    String newType;//新旧程度 全新，九成新，八成新，七成新，七成新以下
    String lat;//	纬度 必传
    String lon;//经度 必传
    String sort;//	价格排序 1价格升序 2价格降序
    private BaseQuickAdapter<GoodBean.DataBean, BaseViewHolder> mAdapter;
    List<GoodBean.DataBean> list = new ArrayList<>();
    private boolean isprice = false;
    private boolean idtongcheng = false;


    @Override
    protected int initLayout() {
        return R.layout.activity_classtype;
    }

    @Override
    protected void initView() {
        titlename = getIntent().getStringExtra("name");
        titleBar.setTitle(titlename);
        if (titlename.equals("企业清库")) {
            userGroup = "企业";
        } else if (titlename.equals("换产品")) {
            classType = "产品";
        } else if (titlename.equals("换服务")) {
            classType = "服务";
        } else if (titlename.equals("闲置换")) {
            isNew = "闲置";
        }else{
            titleBar.setTitle("搜索");
            name=titlename;
        }
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startActivity(SearchActivity.class);
            }
        });

        refresh.setEnableRefresh(true);
        refresh.setEnableAutoLoadMore(true);//启用加载


    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        lat = (String) SPUtils.get(thisActivity, "lat", "");
        lon = (String) SPUtils.get(thisActivity, "lon", "");
        mAdapter = new BaseQuickAdapter<GoodBean.DataBean, BaseViewHolder>(R.layout.item_good_list, list) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, GoodBean.DataBean item) {
                helper.setText(R.id.goodname, item.getGoodsTitle());
                helper.setText(R.id.money, item.getGoodsPrice() + "");
                helper.setText(R.id.city, item.getReleaseCityname() + " " + item.getDistance() + "m");
                helper.setText(R.id.huangood, item.getExchangeClass() + "," + item.getExchangeGoods());
                String[] split = item.getGoodsPic().split("\\|");
                Glide.with(thisActivity).load(split[0]).into(helper.<ImageView>getView(R.id.logo));
                helper.setOnClickListener(R.id.tuhuan, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundlehuan = new Bundle();
                        bundlehuan.putString("id", item.getId());
                        ActivityUtils.startActivity(bundlehuan, GoodinfoActivity.class);
                    }
                });

            }
        };
        rvlist.setLayoutManager(new LinearLayoutManager(thisActivity));
        rvlist.setAdapter(mAdapter);
        GetGood(pageNumber + "", pageSize, typeId, cityId, userGroup, isNew, startPrice, endPrice, name, userType, classType, newType, lat, lon, sort);
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNumber = 1;
                GetGood(pageNumber + "", pageSize, typeId, cityId, userGroup, isNew, startPrice, endPrice, name, userType, classType, newType, lat, lon, sort);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNumber = pageNumber + 1;
                GetGood(pageNumber + "", pageSize, typeId, cityId, userGroup, isNew, startPrice, endPrice, name, userType, classType, newType, lat, lon, sort);
            }
        });

    }

    @OnClick({R.id.reclasstype, R.id.reprice, R.id.recity, R.id.reshaixuan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.reclasstype:
                showpop();
                classtype.setTextColor(getResources().getColor(R.color.select));

                break;
            case R.id.reprice:
                price.setTextColor(getResources().getColor(R.color.select));
                if (isprice == false) {
                    sort = "1";
                    isprice = true;
                    refeish();
                    priceimage.setImageResource(R.mipmap.ic_shengxu);

                } else if (isprice == true) {
                    priceimage.setImageResource(R.mipmap.ic_jiangxu);
                    sort = "2";
                    isprice = false;
                    refeish();
                }

                break;
            case R.id.recity:
                if (idtongcheng == false) {
                    city.setTextColor(getResources().getColor(R.color.select));
                    cityId = (String) SPUtils.get(thisActivity, "citycode", "");
                    refeish();
                    idtongcheng = true;
                } else {
                    city.setTextColor(getResources().getColor(R.color.texthui));
                    cityId = "";
                    refeish();
                    idtongcheng = false;
                }

                break;
            case R.id.reshaixuan:
                shaixuan.setTextColor(getResources().getColor(R.color.select));
                Showpopshaixuan();
                break;
        }
    }

    /**
     * pop
     */
    public void showpop() {
        PopClassType popClassType = new PopClassType(thisActivity, this);
        popClassType.setOnSureClickListener(new PopClassType.OnSureClickListener() {
            @Override
            public void callback(String typeid, String name) {
                classtype.setText(name);
                typeId = typeid;
                refeish();
            }
        });
        popClassType.showPopupWindow(linTitle);
    }

    public void Showpopshaixuan() {
        PopShaiXuan popShaiXuan = new PopShaiXuan(thisActivity,this);
        popShaiXuan.setOnSureClickListener(new PopShaiXuan.OnSureClickListener() {
            @Override
            public void callback(String userTypes, String newTypes, String startPrices, String endPrices, String cityIds) {
                userType=userTypes;
                newType=newTypes;
                startPrice=startPrices;
                endPrice=endPrices;
                cityId=cityIds;
                refeish();
            }
        });
        popShaiXuan.showPopupWindow();

    }


    public void refeish() {
        pageNumber = 1;
        GetGood(pageNumber + "", pageSize, typeId, cityId, userGroup, isNew, startPrice, endPrice, name, userType, classType, newType, lat, lon, sort);
    }

    public void GetGood(String pageNumber, String pageSize, String typeId, String cityId, String userGroup, String isNew, String startPrice, String endPrice, String name, String userType, String classType, String newType, String lat, String lon, String sort) {
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .getGoodsList(pageNumber, pageSize, typeId, cityId, userGroup, isNew, startPrice, endPrice, name, userType, classType, newType, lat, lon, sort)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this, true) {
                    @Override
                    protected void onError(String errorMsg) {
                        Log.e("gooderror", errorMsg + "");
                        if (pageNumber.equals("1")) {
                            if (list != null) {
                                list.clear();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                        refresh.finishRefresh();
                        refresh.finishLoadMore();
                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("good", JsonStr + "");
                        Gson gson = new Gson();
                        GoodBean goodBeans = gson.fromJson(JsonStr, GoodBean.class);
                        if (pageNumber.equals("1")) {
                            if (list != null) {
                                list.clear();
                            }
                        }
                        for (int i = 0; i < goodBeans.getData().size(); i++) {
                            list.add(goodBeans.getData().get(i));
                        }
                        mAdapter.notifyDataSetChanged();
                        refresh.finishRefresh();
                        refresh.finishLoadMore();
                    }
                });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
